package com.pnnd.stream;

/**
 * 'r'       open for reading (default)
 * 'w'       open for writing, truncating the file first
 * 'e'       open for writing, appending to the end of the file if it exists
 * 'b'       binary mode
 */
public class BufferTag {

    private long tag;

    private static long READ = 1;
    private static long WRITE = 1 >> 2;
    private static long EXTEND = 1 >> 3;
    private static long BINARY = 1>>4;


    public BufferTag(long tag){
        this.tag = tag;
    }

    public boolean readonly(){
        return this.tag == READ;
    }

    public boolean writeable(){
        return (this.tag&WRITE) > 0;
    }

    public boolean readable(){
        return (this.tag&READ) > 0;
    }

    public boolean extendable(){
        return (this.tag&EXTEND) > 0;
    }

    public boolean isBinary(){
        return (this.tag&BINARY) > 0;
    }

    @Override
    public String toString(){
        String result = "";

        if(readable()){
            result += 'r';
        }

        if(writeable()){
            result += 'w';
        }

        if(extendable()){
            result += 'e';
        }

        if(isBinary()){
            result += 'b';
        }

        return result;
    }

    public static BufferTag createBy(String mode){

        long tag = 0;

        if(mode.contains("r")){
            tag |= READ;
        }

        if(mode.contains("w")){
            tag |= WRITE;
        }

        if(mode.contains("e")){
            tag |= EXTEND;
        }

        if(mode.contains("b")){
            tag |= BINARY;
        }

        return new BufferTag(tag);
    }

    @Override
    public int hashCode(){
        return Long.hashCode(this.tag);
    }

    @Override
    public boolean equals(Object other){

        if(other instanceof BufferTag){
            return ((BufferTag) other).tag == this.tag;
        }

        return false;
    }
}
